<?php
namespace app\common\service;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\SignatureInvalidException;
use Firebase\JWT\BeforeValidException;
 
class JwtService
{
    // JWT密钥
    protected $key = "123456789ABCDEFGabcdefg";
    
    /**
     * 生成JWT Token
     * @param int $user_id 用户ID
     * @param string $user_name 用户名
     * @return string
     */
    public function generateToken($user_id, $user_name) : string
    {
        $payload = [
            "iss" => $user_id,
            "aud" => $user_name,
            "iat" => time(),
            "nbf" => time(),
            "exp" => time() + 43200 // 12小时有效期
        ];
 
        $jwt = JWT::encode($payload, $this->key, 'HS256');
        return $jwt;
    }
    
    /**
     * 验证JWT Token
     * @param string $token JWT令牌
     * @return array|false 成功返回payload，失败返回false
     */
    public function validateToken($token)
    {
        try {
            $decoded = JWT::decode($token, new Key($this->key, 'HS256'));
            return (array) $decoded;
        } catch (ExpiredException $e) {
            // Token已过期
            return false;
        } catch (SignatureInvalidException $e) {
            // 签名无效
            return false;
        } catch (BeforeValidException $e) {
            // Token未生效
            return false;
        } catch (\Exception $e) {
            // 其他错误
            return false;
        }
    }
}